<?php

class NewsController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
    	 public function filters()
	{
		return array(
			'accessControl',
		);
	}

	public function accessRules()
	{
		return array(
			array('allow',
			      'actions' => array('login'),
			      'users' => array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('add','index','edit','delete'),
				'roles'=>array('admin'),
			),
			array('deny',
			      'users' => array('*'),
			),
		);
	}

	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	public function actionIndex()
	{
        if(isset($_POST['article-grid_c0'])){
           $this->deleteAll($_POST['article-grid_c0']);
        }
		$this->pagetitle = 'Новости - '.Yii::app()->name;
		$this->render('index', array('model'=>Article::model()));
	}

    public function actionView($id)
    {
        $model = News::model()->findByPk($id);
        $this->pagetitle = $model->title.' - '.Yii::app()->name;
        $this->render('view', array('model' => $model));
    }

    public function actionAdd()
    {
        $model = new Article();
        if(isset($_POST['Article']))
        {
            $model->attributes = $_POST['Article'];
            $model->type = 'news';
            $model->author_id = Yii::app()->user->id;

            $model->date_created = date('Y.m.d h:i:s',strtotime($model->date_created));

            if($model->save())
            {
                $this->redirect(array('/news'));
            }
        }
        $this->render('create', array('model' => $model));
    }

    public function actionEdit($id)
    {
        $model = Article::model()->findByPk($id);
        if(isset($_POST['Article']))
        {
            $model->attributes = $_POST['Article'];
            $model->date_created = date('Y.m.d h:i:s',strtotime($model->date_created));
            if($model->save()){
                $this->redirect(array('/news'));
            }
        }
        $this->render('edit', array('model' => $model));

    }

    public function actionDelete($id)
    {
        Article::model()->deleteByPk($id);
        $this->redirect(array('/news'));
    }

    private function deleteAll($ids)
    {
        foreach($ids as $id){
            Article::model()->deleteByPk($id);
        }
    }

    private function uniqueName($fname)
	{
		$ext = end(explode(".",$fname));
		return md5(uniqid()).'.'.$ext;
	}


}